﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RXY_Mall.Core;
using RXY_Mall.Data;
using RXY_Mall.Domain;
using RXY_Mall.Services.Company.Dto;
using System.Data.Entity;
using System.Linq;

namespace RXY_Mall.Services.Company
{
    public class CompanyService : ICompanyService
    {
        private RXY_MallContext db;

        public CompanyService()
        {
            db = new RXY_MallContext();
        }

        /// <summary>
        /// 添加公司
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResponseService<bool>> AddCompany(AddCompanyInput input)
        {
            ResponseService<bool> result = new ResponseService<bool>();
            result.code = 0;
            try
            {
                var company = await GetCompany(input.api_company_id);

                if (company != null)
                {
                    result.msg = "公司编号已存在";
                    return result;
                }
                company = new gw_company()
                {
                    address = input.address,
                    add_time = DateTime.Now,
                    api_company_id = input.api_company_id,
                    api_server_id = input.api_server_id,
                    area = input.area,
                    city_code = input.city_code,
                    contacts_name = input.contacts_name,
                    contacts_phone = input.contacts_phone,
                    country_code = input.country_code,
                    deleted = false,
                    end_time = DateTime.Now.AddDays(30),
                    start_time = DateTime.Now,
                    grade = 1,
                    name = input.company_name,
                    province_code = input.province_code,
                    type = input.company_type,
                    status = 1,
                };

                db.gw_companys.Add(company);
                await db.SaveChangesAsync();

                result.code = 1;
                result.msg = "添加成功";
                result.data = true;
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
                result.code = 2;
                result.msg = ex.Message;
            }
            return result;
        }

        /// <summary>
        /// 获得公司
        /// </summary>
        /// <param name="api_company_id"></param>
        /// <returns></returns>
        public async Task<gw_company> GetCompany(string api_company_id)
        {
            var company = await db.gw_companys.FirstOrDefaultAsync(c => c.api_company_id == api_company_id);
            return company;
        }
    }
}
